package com.tencent.cloud.iov.processor.utils;

import java.util.List;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;

/**
 * 由父接口至子接口进行排序（父接口 < 子接口）
 *
 * @author showxiao
 * @date 2018/4/18
 */
public class TypeMirrorComparator implements java.util.Comparator<TypeMirror> {

        @Override
        public int compare(TypeMirror tm1, TypeMirror tm2) {
            if (tm1 == tm2) {
                return 0;
            }

            if (!(tm1 instanceof DeclaredType)) {
                return -1;
            }

            Element element = ((DeclaredType) tm1).asElement();
            if (!(element instanceof TypeElement)) {
                return -1;
            }

            TypeElement typeElement = (TypeElement) element;
            List<? extends TypeMirror> interfaces = typeElement.getInterfaces();
            if (interfaces == null || interfaces.isEmpty()) {
                return -1;
            }

            for (TypeMirror typeMirror : interfaces) {
                if (compare(typeMirror, tm2) >= 0) {
                    return 1;
                }
            }

            return -1;
        }
    }